package com.foreveross.bsl.common.utils.balance.zookeeper2;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ZK通用watch程序
 *
 * @author hyw
 */
public class ZKCommonWatcher implements Watcher {

	private static final Logger logger = LoggerFactory.getLogger(ZKCommonWatcher.class);

	String watchedPath;
	ZKCommonKeeper zkCommonKeeper;


	public ZKCommonWatcher(ZKCommonKeeper zkCommonKeeper) {
		this.zkCommonKeeper = zkCommonKeeper;
		this.watchedPath = zkCommonKeeper.path;
	}

	public ZKCommonWatcher(ZKCommonKeeper zkCommonKeeper, String path) {
		this.zkCommonKeeper = zkCommonKeeper;
		this.watchedPath = path;
	}

	@Override
	public void process(WatchedEvent event) {
		// 只要该path下面创建/删除node都会促发事件 etc.
		zkCommonKeeper.process();

		String path = event.getPath();

		logger.debug("ZKCommonWatcher WatchedEvent path={}", path);
		logger.debug("ZKCommonWatcher WatchedEvent type={} state={}", event.getType(), event.getState());

		if (event.getType() == Event.EventType.None) {
			// We are are being told that the state of the connection has changed
			switch (event.getState()) {
			case SyncConnected:
				// In this particular example we don't need to do anything here - watches are automatically re-registered with
				// server and any watches triggered while the client was
				// disconnected will be delivered (in order of course)
				break;
			case Expired:
				// It's all over, reconnect...
				/** boolean connected = false; while (!connected) { try {
				 * zkCommonKeeper.rebuild(); zk = zkCommonKeeper.zk;
				 * Thread.sleep(RECONNECT_SLEEP); if (States.CONNECTED ==
				 * zk.getState()) { connected = true;
				 * zkCommonKeeper.bindWatcher(watchedPath); } } catch
				 * (InterruptedException e) { // TODO Auto-generated catch block
				 * e.printStackTrace(); } }
				 */
				break;
			default:
				break;
			}
		} else if (event.getType() == Event.EventType.NodeDeleted) {
			try {
				System.out.println("================>NodeDeleted watchedPath=" + watchedPath);
				// zk.close();
				zkCommonKeeper.bindWatcher(watchedPath); // 由于对某个节点监听是一次性事件，重新建立监听
				// ZKUtil.buildPath(zk, aliveServicePath, CreateMode.PERSISTENT);
				// zk.getChildren(aliveServicePath, new ZKServiceWatcher(zk, serverList, aliveServicePath, listener));
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("watcher:" + watchedPath + " path=" + path);
			if (path != null && path.equals(watchedPath)) {
				// Something has changed on the aliveServicePath, let's find out
			}
			zkCommonKeeper.bindWatcher(watchedPath);
			// zk.getChildren(aliveServicePath, new ZKServiceWatcher(zk, serverList, aliveServicePath, listener));
			// for (String aliveServer : aliveServers) {
			// 	System.out.println("server:" + aliveServer);
			// }
		}
	}
}
